//
//  TPFileManager.m
//  CNTaipingAgent
//
//  Created by Aren on 2/4/15.
//  Copyright (c) 2015 Taiping. All rights reserved.
//

#import "TPFileManager.h"

#define CACHE_RECORD_DOMAIN @"record"
#define CACHE_SPEECH_DOMAIN @"speech"
#define CACHE_PHOTO_DOMAIN  @"photo"

#define CACHE_ADVICE_DOMIN @"head"

@implementation TPFileManager


#pragma mark - content

+ (NSArray *)contentOfFloder:(NSString *)path
{
    if(path == nil) {
        return nil;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *contentOfFolder = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    return contentOfFolder;
}

+ (NSArray *)subDirectoryUnderFloder:(NSString *)path
{
    NSArray *contentOfFolder = [self contentOfFloder: path];
    
    if(contentOfFolder == nil || contentOfFolder.count < 1) {
        return nil;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSMutableArray *folderList = [[NSMutableArray alloc] initWithCapacity:contentOfFolder.count];
    
    for (NSString *itemName in contentOfFolder) {
        
        NSString *fullPath = [path stringByAppendingPathComponent:itemName];
        
        BOOL isDir;
        
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir]) {
            
            if( isDir == YES) {
                [folderList addObject:fullPath];
            }
        }
    }
    
    return folderList;
}

+ (NSArray *)filesUnderFloder:(NSString *)path
{
    NSArray *contentOfFolder = [self contentOfFloder: path];
    
    if(contentOfFolder == nil || contentOfFolder.count < 1) {
        return nil;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSMutableArray *fileList = [[NSMutableArray alloc] initWithCapacity:contentOfFolder.count];
    
    for (NSString *itemName in contentOfFolder) {

        NSString *fullPath = [path stringByAppendingPathComponent:itemName];
        
        BOOL isDir;
        
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir]) {
            
            if( isDir == NO) {
                [fileList addObject:fullPath];
            }
        }
    }
    
    return fileList;
}


#pragma mark - attr


+ (NSDictionary *)fileAttribute:(NSString *)path
{
    if(path == nil) {
        return nil;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ( ![fileManager fileExistsAtPath:path]) {
        return nil;
    }
    
    NSError *error;

    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    
    // deprecated
    // NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
    
    return fileAttributes;
}

+ (NSDate *)createDateOfFile:(NSString *)path
{
    NSDictionary *fileAttributes = [self fileAttribute:path];
    
    NSDate *creationDate = nil;
    
    if (fileAttributes != nil) {
        
        // NSFileCreationDate = "2015-04-09 02:22:06 +0000";
        creationDate = [fileAttributes objectForKey:NSFileCreationDate];
    }
    
    return creationDate;
}

+ (NSNumber *)fileSize:(NSString *)path
{
    NSDictionary *fileAttributes = [self fileAttribute:path];
    
    NSNumber *fileSize = nil;
    
    if (fileAttributes != nil) {
        
        // 文件大小
        fileSize = [fileAttributes objectForKey:NSFileSize];
    }

    return fileSize;
}


#pragma mark - create file

+ (void)copyFileFrom:(NSString *)src to:(NSString *)dest
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:dest]) {
        [fileManager removeItemAtPath:dest error:nil];
    }
    
    NSError *error = nil;
    
    if(![fileManager copyItemAtPath:src toPath:dest error:&error]){

    }
}

+ (void)deleteFileAt:(NSString *)path
{
    NSFileManager *fileManger=[NSFileManager defaultManager];
    
    NSError *error;
    
    [fileManger removeItemAtPath:path error:&error];
}

+ (NSString *)createFileUnderDocument:(NSString *)fileName
{
    NSString * documentdir=[self documentDirectoryPath];
    
    return [self createFileUnder:documentdir forName:fileName];
}

+ (NSString *)createFileUnder:(NSString *)parent forName:(NSString *)fileName
{
    if(fileName == nil || fileName.length < 1) {
        return nil;
    }
    
    if(parent == nil || parent.length < 1) {
        return nil;
    }
    
    NSString *newPath = [parent stringByAppendingPathComponent:fileName];
    
    return [self createFile:newPath deleteOld:YES];
}

+ (NSString *)createFile:(NSString *)fullPath deleteOld:(BOOL)deleteOld
{
    if(fullPath == nil || fullPath.length < 1) {
        return nil;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:fullPath]) {
        
        if(deleteOld) {
            [self deleteFileAt: fullPath];
        } else {
            return fullPath;
        }
    }
    
    if ([fileManager createFileAtPath:fullPath contents:nil attributes:nil] ) {
    }
    
    return fullPath;
}


#pragma mark - create path

+ (NSString *)documentDirectoryPath
{
    NSFileManager *fileManger=[NSFileManager defaultManager];
    
    NSArray *dirs = [fileManger URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    
    NSURL *docDirUrl = [dirs objectAtIndex:0];
    
    NSString *documentdir=[docDirUrl path];
    
    return documentdir;
}

+ (NSString *)createFolderUnderDocument:(NSString *)folderName
{
    NSString * documentdir=[self documentDirectoryPath];
    
    return [self createFolderUnderPath:documentdir forName:folderName];
}

+ (NSString *)createFolderUnderPath:(NSString*)parent forName:(NSString *)folderName
{
    if(folderName == nil || folderName.length < 1) {
        return nil;
    }

    NSString *newPath = [parent stringByAppendingPathComponent:folderName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // create if not exist
    if(![fileManager fileExistsAtPath:newPath isDirectory:nil]) {
        
        NSError *error;
        
        [fileManager createDirectoryAtPath:newPath withIntermediateDirectories:NO attributes:nil error:&error];
    }
    
    return newPath;
}

// 检查目录是否存在，不存在则创建
- (BOOL)checkFolder:(NSString *)path
{
    if(path == nil || path.length < 1) {
        return NO;
    }
    
    if( [path isEqualToString:@"/"] ) {
        return YES;
    }
    
    BOOL isDirectory = NO;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // create if not exist
    if(![fileManager fileExistsAtPath:path isDirectory:&isDirectory]) {
        
        NSRange range = [path rangeOfString:@"/" options:NSBackwardsSearch];
        
        if(range.length > 0) {
            
            NSString *parent = @"";
            BOOL parentExist = NO;
            
            if(range.location == 0 ) {
                parentExist = YES;
            } else if(range.location == (path.length - 1) ) {
                parent = [path substringToIndex:range.location];
            } else {
                parent = [path substringToIndex:range.location];
            }
            
            parentExist = [self checkFolder:parent];
            
            if (!parentExist) {
                return NO;
            }
            
        } else {
            return NO;
        }
        
        NSError *error;
        
        return [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
    }
    
    return YES;
}


#pragma mark - cache path

+ (NSString *)recordFileFRootPath
{
    NSString *rootPath = [self createFolderUnderDocument:CACHE_RECORD_DOMAIN];
    
    return rootPath;
}

+ (NSString *)recordFilePathForCalltask:(NSNumber *)taskId
{
    if(taskId == nil) {
        return nil;
    } else {
        
        NSString *path = [self createFolderUnderDocument:CACHE_RECORD_DOMAIN];
        
        NSString *voiceName = [NSString stringWithFormat:@"%@%d.m4a",CACHE_RECORD_DOMAIN,taskId.intValue];
        
        return [path stringByAppendingFormat:@"/%@", voiceName];
    }
}

+ (NSString *)speechFilePathForCalltask:(NSNumber *)taskId
{
    if(taskId == nil) {
        return nil;
    } else {
        
        NSString *path = [self createFolderUnderDocument:CACHE_SPEECH_DOMAIN];
        
        NSString *voiceName = [NSString stringWithFormat:@"%@%d.spx",CACHE_SPEECH_DOMAIN,taskId.intValue];
        
        return [path stringByAppendingFormat:@"/%@", voiceName];
    }
}

+ (NSString *)photoFilePathForCalltask:(NSNumber *)taskId
{
    if(taskId == nil) {
        return nil;
    } else {
        
        NSString *path = [self createFolderUnderDocument:CACHE_PHOTO_DOMAIN];
        
        NSString *photoName = [NSString stringWithFormat:@"%@%d.png",CACHE_PHOTO_DOMAIN,taskId.intValue];
        
        return [path stringByAppendingFormat:@"/%@", photoName];
    }
}


#pragma mark - clear cache

+ (void)clearAllCacheFile
{
    [self clearRecordCacheFile];
    
    [self clearSpeechCacheFile];
    
    [self clearPhotoCacheFile];
}

+ (void)clearRecordCacheFile
{
    NSString *path = [self createFolderUnderDocument:CACHE_RECORD_DOMAIN];
    
    [self clearCacheFolder:path extension:nil];
}

+ (void)clearSpeechCacheFile
{
    NSString *path = [self createFolderUnderDocument:CACHE_SPEECH_DOMAIN];
    
    [self clearCacheFolder:path extension:nil];
}

+ (void)clearPhotoCacheFile
{
    NSString *path = [self createFolderUnderDocument:CACHE_PHOTO_DOMAIN];
    
    [self clearCacheFolder:path extension:nil];
}

+ (void)clearCacheFile:(NSString *)filePath
{
    NSFileManager * fileManger=[NSFileManager defaultManager];
    
    NSError * error;
    
    [fileManger removeItemAtPath:filePath error:&error];
}

+ (void)clearCacheFolder:(NSString *)folderPath extension:(NSString *)extension
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:folderPath error:NULL];
    
    NSEnumerator *enumerator = [contents objectEnumerator];
    
    NSString *filename = nil;
    
    while ((filename = [enumerator nextObject])) {
        
        if(extension != nil && extension.length >0 && ![[filename pathExtension] isEqualToString:extension]) {
            continue;
        }
        
        [fileManager removeItemAtPath:[folderPath stringByAppendingPathComponent:filename] error:NULL];
    }
}

+ (void)savePhotoFor:(NSData *)imageData nameStr:(NSString *)nameStr
{
    NSString *documentStr = [self createFolderUnderDocument:CACHE_ADVICE_DOMIN];
    NSString *filePath = [documentStr stringByAppendingPathComponent:nameStr];
    NSLog(@"filePath=%@",filePath);
    [imageData writeToFile:filePath atomically:YES];
}



+ (NSData *)getPhoto:(NSString *)nameStr{
    NSString *tempDir = [[self documentDirectoryPath] stringByAppendingPathComponent:CACHE_ADVICE_DOMIN] ;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [tempDir stringByAppendingPathComponent:nameStr];

    if ([fileManager fileExistsAtPath:filePath]) {
            NSData *imageData = [[NSData alloc]initWithContentsOfFile:filePath];
            return imageData;
        }
    return nil;
}
+ (void)deleteImageData:(NSString *)nameStr{
    NSString *docDir = [[self documentDirectoryPath] stringByAppendingPathComponent:CACHE_ADVICE_DOMIN];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [docDir stringByAppendingPathComponent:nameStr];
    if ([fileManager fileExistsAtPath:filePath]) {
       BOOL isSuccess = [fileManager removeItemAtPath:filePath error:nil];
        NSLog(@"%d",isSuccess);
    }
}

+ (BOOL)getPhotoStr:(NSString *)nameStr{
    NSString *tempDir = [[self documentDirectoryPath] stringByAppendingPathComponent:CACHE_ADVICE_DOMIN] ;
    NSString *filePath = [tempDir stringByAppendingPathComponent:nameStr];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:filePath]) {
        return YES;
    }
    return NO;
}

@end

